#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QComboBox>
#include <QtGui/QStandardItemModel>
#include <QtGui/QTableView>
#include <QtGui/QHeaderView>
#include <QtGui/QMessageBox>
#include <QtCore/QModelIndex>
#include <QtCore/QTextStream>
#include <QtCore/QVariant>
#include <QtCore/QDateTime>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <QtDebug>
#include <QString>
#include "linkdevicedialog.h"
#include "spindelegate.h"

LinkDeviceDialog::LinkDeviceDialog(QWidget *parent) :
    QDialog(parent)
{
    createItems();
    initModel();
    connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(dataChangedSlot(QModelIndex)));
    this->setWindowTitle(tr("联动类型设置"));
    this->setFixedSize(QSize(380, 450));//this->resize(QSize(800, 480));
    connect(this->parentWidget(), SIGNAL(closedialog()), this, SLOT(close()));

}
LinkDeviceDialog::~LinkDeviceDialog()
{


}
void LinkDeviceDialog::createItems()
{
    okPushButton = new QPushButton(tr("确定"), this);
    okPushButton->setGeometry(QRect(55, 420, 85, 27));
    connect(okPushButton, SIGNAL(clicked()), this, SLOT(okToContinue()));
    cancelPushButton = new QPushButton(tr("取消"), this);
    cancelPushButton->setGeometry(QRect(215, 420, 85, 27));
    connect(cancelPushButton, SIGNAL(clicked()), this, SLOT(close()));

    model = new QStandardItemModel (rowNumber, columnNumber, this);
    tableview = new QTableView(this);
    tableview->setModel(model);
    tableview->setGeometry(QRect(20, 10, 330, 395));
//    tableview->verticalHeader()->setResizeMode(QHeaderView::Fixed);
    tableview->verticalHeader()->setVisible(false);
    tableview->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
}
void LinkDeviceDialog::initModel()
{
    model->setHeaderData(0, Qt::Horizontal, tr("类型编码"));
    model->setHeaderData(1, Qt::Horizontal, tr("设备类型"));
    model->setHeaderData(2, Qt::Horizontal, tr("快捷按键"));

    spinDelegate *nodeId = new spinDelegate(0);
    tableview->setItemDelegateForColumn(0, nodeId);


    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.setForwardOnly(true);
    query.exec(QString("select * from linkdevice"));
    while (query.next())
    {
        model->setData(model->index(query.at(), 0, QModelIndex()), query.value(0).toInt());
        model->setData(model->index(query.at(), 1, QModelIndex()), query.value(1).toString());
        model->setData(model->index(query.at(), 2, QModelIndex()), query.value(2).toString());
     }

    QSqlDatabase::database().commit();
}

void LinkDeviceDialog::dataChangedSlot(const QModelIndex &index)
{

        QModelIndex currentIndex[3];

        QTime time;
//        QModelIndex index = model->index(1,2,QModelIndex());
        qDebug() << index.row() << index.column() << index.model()->data(index).toString();
        time.restart();
        /*There is a space behind SET,do not forget*/
        QSqlDatabase::database().transaction();
        for (int j = 0;j < 3;j++)
        {
            currentIndex[j] = model->index(index.row(), j, QModelIndex());
        }


        QSqlQuery query;
        query.clear();
        query.prepare(QString("UPDATE linkdevice SET "
                              "devicename=?, letter=?"
                              "WHERE id = %1").arg((index.row()+1)));

         if(index.column() == 1)
         {
             QString devicestr = currentIndex[1].model()->data(currentIndex[1]).toString().trimmed();
             this->deBlank(devicestr);

             QSqlQuery queryDeviceSelect;
             queryDeviceSelect.exec(QString("select id from linkdevice where devicename is '%1'").arg(devicestr));
             if (queryDeviceSelect.next())
             {
                     query.addBindValue(QString(tr("")));
                     model->setData(model->index(index.row(), index.column(), QModelIndex()), QString(tr("")));
             }
             else
             {
//                 query.addBindValue(currentIndex[1].model()->data(currentIndex[1]).toString().trimmed());

                 query.addBindValue(devicestr);
                 model->setData(model->index(index.row(), index.column(), QModelIndex()), devicestr);
             }
             query.addBindValue(currentIndex[2].model()->data(currentIndex[2]).toString().left(1));
         }
         else if(index.column() == 2)
         {
             query.addBindValue(currentIndex[1].model()->data(currentIndex[1]).toString());

             QString str = currentIndex[2].model()->data(currentIndex[2]).toString().left(1);
             if(str >= QString(tr("a")) && str <= QString(tr("z")))
             {
                 QSqlQuery querySelect;
                 querySelect.exec(QString("select id from linkdevice where letter is '%1'").arg(str));
                 if (querySelect.next())
                 {
                         query.addBindValue(QString(tr("")));
                         model->setData(model->index(index.row(), index.column(), QModelIndex()), QString(tr("")));
                 }
                 else
                 {
                     query.addBindValue(currentIndex[2].model()->data(currentIndex[2]).toString().left(1));
                 }
             }
             else
             {
                 query.addBindValue( QString(tr("")));
                 model->setData(model->index(index.row(), index.column(), QModelIndex()), QString(tr("")));

             }
         }

//            qDebug() <<currentIndex[1].model()->data(currentIndex[1]).toString() <<"str"<<str;

            bool bSuccess = query.exec();
            if (!bSuccess)
            {
                QSqlError lastError = query.lastError();
                qDebug() << lastError.driverText()
                         << QString(QObject::tr("update error"));
            }
            QSqlDatabase::database().commit();
}

void LinkDeviceDialog::okToContinue()
{
}
void LinkDeviceDialog::deBlank(QString &strs)
{
    int len = strs.length();
    for(int i = 0;i<len;i++)
    {
        if (strs.at(i).isSpace())
        {
            strs.remove(i,1);
        }
    }
}

